package com.miao.websecurity.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.miao.common.entity.R;
import com.miao.common.utils.JWTUtil;
import com.miao.common.utils.TelCodeUtil;
import com.miao.websecurity.entity.Admin;
import com.miao.websecurity.entity.RoleAdmin;
import com.miao.websecurity.entity.SysRole;
import com.miao.websecurity.entity.vo.AdminRoleVO;
import com.miao.websecurity.entity.vo.AdminVO;
import com.miao.websecurity.entity.vo.ResetPasswordVO;
import com.miao.websecurity.service.AdminService;
import com.miao.websecurity.service.RoleAdminService;
import com.miao.websecurity.service.SysRoleService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author MiaoWenqing
 * @description: 管理员
 * @date 2021/2/1 17:49
 */
@RestController
@RequestMapping("/admin")
public class AdminController {


    @Resource
    private AdminService adminService;

    @Resource
    private SysRoleService sysRoleService;

    @Resource
    private RoleAdminService roleAdminService;

    @Resource
    private TelCodeUtil telCodeUtil;


    /**
     * 添加平台管理员
     *
     * @param addAdmin 管理员
     * @return R
     */
    @PostMapping("/add")
    public R adminAdd(@RequestBody Admin addAdmin, @RequestHeader(value = "access-token") String token) {
        QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
        adminQueryWrapper.eq("admin_tel",addAdmin.getAdminTel());
        Admin one = this.adminService.getOne(adminQueryWrapper);
        if (null!=one){
            return new R(2001,"手机号已存在",null);
        }
        addAdmin.setCreateTime(new Date());
        String s = JWTUtil.analysisToken(token);
        Map map = JSON.parseObject(s, Map.class);
        Admin admin = this.adminService.getById(map.get("adminId").toString()); //1平台 0店铺
        if (admin.getAdminType() == 1 && null == admin.getStoreId()) {
            //平台管理员
            addAdmin.setAdminType(1);
            addAdmin.setStoreId(null);

        } else {
            //店铺管理员
            addAdmin.setAdminType(0);
            addAdmin.setStoreId(admin.getStoreId());
        }
        addAdmin.setAdminPasswd(new BCryptPasswordEncoder().encode("123456"));

        if (this.adminService.save(addAdmin)) {
            return R.ok();
        } else {
            return R.error();
        }
    }


    /**
     * 修改 员工和管理员信息
     *
     * @param admin
     * @return
     */

    @PostMapping("/edit")
    public R adminEdit(@RequestBody Admin admin) {
        QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
        adminQueryWrapper.eq("admin_tel",admin.getAdminTel());
        Admin one = this.adminService.getOne(adminQueryWrapper);
        if (null!=one){
            return new R(2001,"手机号已存在",null);
        }
        Admin adminOld = this.adminService.getById(admin.getAdminId());
        adminOld.setAdminName(admin.getAdminName());
        adminOld.setAdminTel(admin.getAdminTel());
        if (this.adminService.saveOrUpdate(adminOld)) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    /**
     * 删除管理员
     *
     * @param adminId
     * @return
     */

    @GetMapping("/del")
    public R adminDel(Integer adminId) {
        if (this.adminService.removeById(adminId)) {
            return R.ok();
        } else {
            return R.error();
        }
    }


    /**
     * 获取所有管理员
     *
     * @return R
     */
    @GetMapping("/all")
    public R adminAllSuper(@RequestHeader(value = "access-token") String token) {

        String s = JWTUtil.analysisToken(token);
        Map map = JSON.parseObject(s, Map.class);
        Admin admin = this.adminService.getById(map.get("adminId").toString()); //1平台 0店铺
        QueryWrapper<Admin> admin_type = new QueryWrapper<Admin>();
        if (admin.getAdminType() == 1 && null == admin.getStoreId()) {
            //平台管理员
            admin_type.eq("admin_type", 1);
        } else {
            //店铺管理员
            admin_type.eq("admin_type", 0);
            admin_type.eq("store_id",admin.getStoreId());
        }
        List<Admin> list = this.adminService.list(admin_type);


        ArrayList<AdminVO> adminVOS = new ArrayList<>();
        list.forEach(item->{
            AdminVO adminVO = new AdminVO();
            adminVO.setAdminId(item.getAdminId());
            adminVO.setAdminName(item.getAdminName());
            adminVO.setAdminTel(item.getAdminTel());
            adminVO.setCreateTime(item.getCreateTime());
            adminVO.setLastLoginTime(item.getLastLoginTime());
            List<SysRole> adminRoles = this.roleAdminService.getAdminRoleById(item.getAdminId());
            adminVO.setSysRoles(adminRoles);
            adminVOS.add(adminVO);
        });
        return R.ok(adminVOS);
    }


    /**
     * 获取角色
     * @return
     */
    @GetMapping("/adminRole")
    public R adminRole(@RequestHeader(value = "access-token") String token){
        String s = JWTUtil.analysisToken(token);
        Map map = JSON.parseObject(s, Map.class);
        List<SysRole> adminRoleById = this.roleAdminService.getAdminRoleById(Integer.valueOf(map.get("adminId").toString()));
        for (SysRole role : adminRoleById) {
            if (role.getRoleId().equals("1")){
                QueryWrapper<SysRole> sysRoleServiceQueryWrapper = new QueryWrapper<>();
                sysRoleServiceQueryWrapper.eq("role_type",1);
                List<SysRole> list = this.sysRoleService.list(sysRoleServiceQueryWrapper);
                 return R.ok(list);
            }
            if (role.getRoleId().equals("3")){
                QueryWrapper<SysRole> sysRoleServiceQueryWrapper = new QueryWrapper<>();
                sysRoleServiceQueryWrapper.eq("role_type",0);
                List<SysRole> list = this.sysRoleService.list(sysRoleServiceQueryWrapper);

                return R.ok(list);
            }
        }

        return R.ok(adminRoleById);
    }


    /**
     * 重置密码
     *
     * @param resetPasswordVO 重置密码
     * @return R
     */
    @PostMapping("/resetPassword")
    public R resetPassword(@RequestBody ResetPasswordVO resetPasswordVO) {


        QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
        adminQueryWrapper.eq("admin_tel", resetPasswordVO.getTel());
        Admin admin = this.adminService.getOne(adminQueryWrapper);

        if (null == admin) {
            return R.error("账号不存在");

        }
        if (!this.telCodeUtil.checkTelCode(resetPasswordVO.getTel(), resetPasswordVO.getCode())) {
            return R.error("验证码错误");
        }


        admin.setAdminPasswd(resetPasswordVO.getNewPwd());
        if (this.adminService.saveOrUpdate(admin)) {
            return R.ok();
        }
        return R.error();

    }



    @PostMapping("/editRole")
    public R editAdminRole(@RequestBody  AdminRoleVO adminRoleVO){
        QueryWrapper<RoleAdmin> roleAdminQueryWrapper = new QueryWrapper<>();
        roleAdminQueryWrapper.eq("admin_id",adminRoleVO.getAdminId());
        this.roleAdminService.remove(roleAdminQueryWrapper);
        ArrayList<RoleAdmin> roleAdmins = new ArrayList<>();

        adminRoleVO.getRoleIds().forEach(item->{
            roleAdmins.add(new RoleAdmin(item,adminRoleVO.getAdminId()));
        });


        if (this.roleAdminService.saveBatch(roleAdmins)) {
            return R.ok();
        }else {
            return R.error();
        }
    }


    @GetMapping("/adminInfo")
    public R adminInfo(@RequestHeader(value = "access-token") String token){
        String s = JWTUtil.analysisToken(token);
        Map map = JSON.parseObject(s, Map.class);
        Admin admin = this.adminService.getById(map.get("adminId").toString());
        admin.setAdminPasswd(null);
        return R.ok(admin);

    }


}
